<template lang="">
  <div>
      <van-nav-bar
        title="查看位置"
        left-text="返回"
        left-arrow
        @click-left="$router.go(-1)"
      />
      <div
        id="allmap"
        ref="allmap"
        class="allmap"
      ></div>
  </div>
</template>
<script>

import BMap from 'BMap'

export default {
  name: 'map',
  props: {
    key: String
  },
  data () {
    return {
      position: '',
      location: {
      },
      isMapShow: false,
      isLoaded: false
    }
  },
  mounted () {
    setTimeout(() => {
      this.isMapShow = true
      if (this.isLoaded === false) {
        this.getLocation()
      }
      this.isLoaded = true
    })
  },

  methods: {
    initMap (pos) {
      var that = this
      const map = new BMap.Map('allmap')
      map.centerAndZoom(pos, 16)
      // 设置定位按钮位置
      var opts = { anchor: 'BMAP_ANCHOR_BOTTOM_RIGHT' }
      // 将定位控件添加到地图上
      map.addControl(new BMap.GeolocationControl(opts))
      // 设置缩放按钮位置及类型
      var ove = { anchor: 'BMAP_ANCHOR_TOP_RIGHT', type: 'BMAP_NAVIGATION_CONTROL_ZOOM' }
      // 添加缩放按钮
      map.addControl(new BMap.NavigationControl(ove))
      map.enableScrollWheelZoom(true)
      var geoc = new BMap.Geocoder({ extensions_town: true })
      map.addEventListener('click', function (e) {
        var pt = e.point
        map.clearOverlays()

        var marker2 = new BMap.Marker(pt) // 创建标注
        map.addOverlay(marker2) // 将标注添加到地图中
        geoc.getLocation(pt, function (rs) {
          var addComp = rs.addressComponents
          that.position = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber
        })
      })
    },
    getLocation () {
      const position = new BMap.Geolocation()
      position.enableSDKLocation()
      position.getCurrentPosition(pos => {
        this.position = pos.address.province + pos.address.city + pos.address.district
        this.initMap(this.key)
      })
    },
    onClickLeft () {
      this.isMapShow = false
    }
  }

}
</script>
<style lang="less" scoped>
#allmap {
  width: 100vh;
  height: calc(100vh - 46px);
}
</style>
